// 微内核实现
const MicroKernel = function () {
    this.modules = new Map();
    this.eventBus = new EventTarget();
};

MicroKernel.prototype.registerModule = function (name, module) {
    this.modules.set(name, module);
    module.init(this);
};

MicroKernel.prototype.emitEvent = function (eventName, data) {
    const event = new CustomEvent(eventName, { detail: data });
    this.eventBus.dispatchEvent(event);
};

MicroKernel.prototype.onEvent = function (eventName, callback) {
    this.eventBus.addEventListener(eventName, (e) => callback(e.detail));
};

// 定义全局 kernel
const kernel = new MicroKernel();

// UI 模块
const UIModule = {
    init(kernel) {
        kernel.onEvent('popup-ready', () => {
            console.log('Popup-ready event received, emitting render-ui');
            kernel.emitEvent('render-ui', { message: 'Hello World' });
        });
    }
};

// AI 模块
const AIModule = {
    init(kernel) {
        console.log('AI Module initialized');
        // 监听 render-ui 事件，修改消息内容
        kernel.onEvent('render-ui', (data) => {
            console.log('AI Module intercepted render-ui event:', data);
            // 修改消息内容，添加 AI 处理标记
            data.message = data.message + ' (Processed by AI)';
            // 触发新事件 render-ui-updated
            kernel.emitEvent('render-ui-updated', data);
        });
    }
};

// 注册模块
kernel.registerModule('ui', UIModule);
kernel.registerModule('ai', AIModule);

console.log('Microkernel initialized in background.js');

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('Message received from popup:', message);
    if (message.type === 'popup-ready') {
        let responded = false;
        // 监听 render-ui-updated 事件（由 AIModule 触发）
        kernel.onEvent('render-ui-updated', (data) => {
            console.log('Render-ui-updated event triggered, sending response:', data);
            sendResponse(data);
            responded = true;
        });

        // 触发 popup-ready 事件
        kernel.emitEvent('popup-ready');

        // 如果事件未触发，设置一个超时以确保响应
        setTimeout(() => {
            if (!responded) {
                console.error('Render-ui-updated event not triggered, sending default response');
                sendResponse({ message: 'Fallback: Hello World' });
            }
        }, 1000); // 1秒超时
    }
    return true; // 保持消息通道开放
});